package com.simple.trade.service.vm.impl;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.simple.common.entity.ResData;
import com.simple.common.entity.constant.Payment;
import com.simple.common.entity.dto.pay.vm.QueryTradeDto;
import com.simple.common.entity.dto.pay.vm.QueryTradeRspDto;
import com.simple.common.entity.po.sys.ChannelComp;
import com.simple.common.entity.po.sys.Product;
import com.simple.common.entity.po.sys.Trade;
import com.simple.common.entity.req.vm.pay.QueryTradeReq;
import com.simple.common.entity.vo.pay.QueryTradeRes;
import com.simple.trade.holder.PayContext;
import com.simple.trade.service.vm.QueryTradeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author yasud
 * @date 2020年10月10日 12:00
 * @description
 */
@Slf4j
@Service
public class QueryTradeServiceImpl extends AbstractService implements QueryTradeService {


    /**
     * 查询交易
     *
     * @param req
     * @return
     */
    @Override
    public ResData<QueryTradeRes> queryTrade(QueryTradeReq req) {
        log.info("查询商户订单{}", req.getOrderNo());
        Trade trade = tradeApi.findByPropertyOne_(Maps.newHashMap(ImmutableMap.of(
                "merchant_order_no", req.getOrderNo(),
                "app_id", req.getAppId()
        )));
        Preconditions.checkNotNull(trade, "订单不存在");
        PayContext.current().iam(trade);

        log.info("商户订单{}的对象为{}", req.getOrderNo(), trade);
        Pair<ChannelComp, Product> pair = findChannelAnProduct();
        ChannelComp channel = pair.getLeft();
        Product product = pair.getRight();
        if (trade.getStatus() != Trade.Status.SUCCESS) {
            QueryTradeDto queryTradeDto = QueryTradeDto.generateDto(trade, PayContext.current().getContext(), req.getExtra(), channel, product);
            ResData<QueryTradeRspDto> queryTradeRspDtoResData = forwardToChannel(queryTradeDto, channel, Payment.PAY_TYPE.VM_QUERY_TRADE, QueryTradeRspDto.class);
            if (queryTradeRspDtoResData.isOk()) {
                QueryTradeRspDto rspDto = queryTradeRspDtoResData.getData();
                Trade dtoTrade = rspDto.getTrade();
                Preconditions.checkNotNull(dtoTrade, "返回订单不能为空!!");
                if (dtoTrade.getStatus() == Trade.Status.SUCCESS) {
                    if (Objects.isNull(dtoTrade.getCompleteTime())) {
                        dtoTrade.setCompleteTime(new Date());
                    }
                }
                tradeApi.updateById_(dtoTrade);
                log.info("商户订单{}查询渠道成功，返回如下{}", req.getOrderNo(), rspDto);
                return ResData.ok(generateTradeRes(rspDto));
            } else {
                log.info("商户订单{}查询渠道失败, 返回原因{}", req.getOrderNo(), queryTradeRspDtoResData.getMsg());
                return ResData.error(queryTradeRspDtoResData.getMsg());
            }
        }
        else {
            QueryTradeRspDto rspDto = new QueryTradeRspDto();
            rspDto.setTrade(trade);
            return ResData.ok(generateTradeRes(rspDto));
        }
    }

    /**
     * 创建
     *
     * @param queryTradeRspDto
     * @return
     */
    private QueryTradeRes generateTradeRes(QueryTradeRspDto queryTradeRspDto) {
        Trade trade = queryTradeRspDto.getTrade();
        QueryTradeRes queryTradeRes = new QueryTradeRes();
        queryTradeRes.setSerialNo(trade.getId());
        queryTradeRes.setOrderNo(trade.getMerchantOrderNo());
        queryTradeRes.setCurrency(trade.getCurrency());
        queryTradeRes.setAmount(trade.getAmount());
        queryTradeRes.setPayStatus(trade.getStatus());
        queryTradeRes.setPayMsg(trade.getMsg());
        queryTradeRes.setRemark(trade.getOrderDesc());
        //退款一部分下面再弄
        queryTradeRes.setRefundStatus(trade.getRefundStatus());
        queryTradeRes.setRefundAmount(trade.getRefundAmount());
        return queryTradeRes;
    }
}
